package com.chagee.channel.server.util;

import org.mapstruct.Named;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * LocalDateTransfer
 *
 * @author CHENPINGYUN
 * @version 2024/02/26 10:56
 **/
public class LocalDateTimeUtil {
	public static DateTimeFormatter YY_MM_DD = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	public static DateTimeFormatter YYMMDD = DateTimeFormatter.ofPattern("yyyyMMdd");



	@Named("toDate")
	public static Date toDate(LocalDateTime currentDate) {
		if (currentDate == null) {
			return null;
		}

		Instant instant = currentDate.atZone(ZoneId.systemDefault()).toInstant();
		return Date.from(instant);
	}

	@Named("toLocalDateTime")
	public static LocalDateTime toLocalDateTime(Date createTime) {
		if (createTime == null) {
			return null;
		}
		Instant instant = createTime.toInstant();
		return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
	}

	@Named("toLocalDate")
	public static LocalDate toLocalDate(String chineseDate) {
		// 创建一个映射表，将中文数字转换为阿拉伯数字
		Map<String, Integer> chineseToNumber = new HashMap<>();
		chineseToNumber.put("〇", 0);
		chineseToNumber.put("一", 1);
		chineseToNumber.put("二", 2);
		chineseToNumber.put("三", 3);
		chineseToNumber.put("四", 4);
		chineseToNumber.put("五", 5);
		chineseToNumber.put("六", 6);
		chineseToNumber.put("七", 7);
		chineseToNumber.put("八", 8);
		chineseToNumber.put("九", 9);
		try {
		// 将中文日期字符替换为阿拉伯数字
		StringBuilder numericDate = new StringBuilder();
		for (char ch : chineseDate.toCharArray()) {
			String strCh = String.valueOf(ch);
			if (chineseToNumber.containsKey(strCh)) {
				numericDate.append(chineseToNumber.get(strCh));
			} else if (strCh.equals("年") || strCh.equals("月") || strCh.equals("日")) {
				numericDate.append(" ");
			}
		}

		// 处理结果，得到格式化的日期字符串
		String formattedDate = numericDate.toString().trim().replace(" ", "-");

		// 使用 DateTimeFormatter 解析日期
		DateTimeFormatter formatter = new DateTimeFormatterBuilder()
				.appendOptional(DateTimeFormatter.ofPattern("yyyy-M-d")) // 允许单数字格式
				.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd")) // 允许双数字格式
				.toFormatter();


		// 解析字符串为 LocalDate
		LocalDate date = LocalDate.parse(formattedDate, formatter);
		String format = date.format(YY_MM_DD);

			return LocalDate.parse(format, YY_MM_DD);
		} catch (DateTimeParseException e) {
			e.printStackTrace();
			return null; // 处理解析异常
		}
	}


	public static String getLocalDateTime(LocalDateTime datetime, DateTimeFormatter formater) {
		if (datetime == null) {
			return null;
		}
		if (formater == null) {
			formater = YY_MM_DD;
		}
		return datetime.format(formater);
	}
}
